﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbobsCOM;
using SAPbouiCOM;
using System.Collections;

namespace BoAddonBiz_FreightForwarder
{
    public class B1Form_Message : SAPBoAddon.B1Form
    {
        private bool IsFee = false;
        private string ParentItemUID = string.Empty;
        private string ParentFormUID = string.Empty;
        public B1Form_Message()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_Message_frm_ItemEvent);
        }

        void B1Form_Message_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            { }
            else
            {
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    if (pVal.ItemUID == "btn_send")
                    {
                        if (Send())
                            this.CurrentForm.Close();
                    }
                    if (pVal.ItemUID == "btn_search")
                    {
                        Search();
                    }
                }
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    if (pVal.ItemUID == "grid" && pVal.Row == -1)
                    {
                        Grid grid = this.CurrentForm.Items.Item("grid").Specific;
                        if (!String.IsNullOrEmpty(pVal.ColUID))
                            Utils.ReSort(grid, pVal.ColUID);//排序
                    }
                }
            }
        }
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            this.FormSetting.FormType = B1FormTypes.ado_AVA_FF_Message;
            this.FormSetting.FormFileName = "AVA_FF_MessageForm.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            if (InitPar.KeyValue.Split(';').Count() > 1)
            {
                //费用审核
                if (InitPar.KeyValue.Split(';')[0] == "FeeApparel")
                {
                    IsFee = true;
                    ParentItemUID = InitPar.KeyValue.Split(';')[1].ToString();
                    ParentFormUID = InitPar.FatherFormUID;

                    Search(InitPar.parObject.ToString());
                }
            }
            else
                IsFee = false;
        }
        #region 查找用户
        private void Search()
        {
            string txt = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "3").ToString().Trim();
            string Pars_Search = this.CurrentForm.DataSources.UserDataSources.Item("Sch_Pars").ValueEx.Trim();  // 从父窗体传递来的 查询的参数 by WangPeng 2012年9月24日 16:56:13
            string sql = String.Format(@"select t0.USERID,t1.empID,t0.USER_CODE, t1.firstName+ISNULL(t1.middleName,'')+t1.lastName as ChnName,t1.jobTitle as EngName 
                                                            from OUSR t0 left join OHEM t1 on t0.USERID = t1.userId 
                                                            where  t1.jobTitle like '%{0}%' {1} order by t1.jobTitle  ", txt, Pars_Search);

            Search(sql);
        }
        private void Search(string SQL)
        {
            /*
SELECT T3.USERID,T1.empId,T3.USER_CODE,T1.Firstname + T1.LastName ChnName,T0.JobTitle EngName FROM OHEM T0
    INNER JOIN OHEM T1 ON T0.Dept = T1.Dept
    INNER JOIN OHPS T2 ON T1.Position = T2.PosID 
    INNER JOIN OUSR T3 ON T0.UserID = T3.UserID
Where T2.Name = '客服' And T3.UserID = 10             
             */
            Grid grid = this.CurrentForm.Items.Item("grid").Specific;

            DataTable result = this.CurrentForm.DataSources.DataTables.Item("DT_Result");

            result.ExecuteQuery(SQL);
            grid.DataTable = result;
            grid.Columns.Item(0).Visible = false;
            grid.Columns.Item(1).Visible = false;
            grid.Columns.Item(2).Visible = false;
            grid.Columns.Item(3).Editable = false;
            grid.Columns.Item(3).TitleObject.Caption = "英文名";
            grid.Columns.Item(4).Editable = false;
            grid.Columns.Item(4).TitleObject.Caption = "中文名";
            grid.AutoResizeColumns();
            if (result.Rows.Count == 0 || (result.Rows.Count == 1 && result.GetValue("USERID", 0) == 0))
            {
                SBOApp.MessageBox("没有查到符合条件的员工数据，请更换条件重新检索");
            }
        }
        #endregion
        private bool Send()
        {
            Grid grid = this.CurrentForm.Items.Item("grid").Specific;

            for (int i = 0; i < grid.Rows.Count; i++)
            {
                if (grid.Rows.IsSelected(i))
                {
                    string userEngName = grid.DataTable.GetValue("EngName", grid.GetDataTableRowIndex(i));
                    string USER_CODE = grid.DataTable.GetValue("USER_CODE", grid.GetDataTableRowIndex(i)).ToString().Trim();
                    if (IsFee)
                        return FeeSend(USER_CODE);
                    else
                        return BusinessSend(USER_CODE, userEngName);
                }
            }
            SBOApp.StatusBar.SetText("请先选择发送用户", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
            return false;
        }
        private bool BusinessSend(string USER_CODE, string userEngName)
        {
            string ParentUID = this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value;
            Form parentForm = this.SBOApp.Forms.Item(ParentUID);
            string ObjType = parentForm.TypeEx;
            IEnumerator dbdsEnumerator = parentForm.DataSources.DBDataSources.GetEnumerator();
            while (dbdsEnumerator.MoveNext())
            {
                DBDataSource dbds = dbdsEnumerator.Current as DBDataSource;
                if (!new System.Text.RegularExpressions.Regex(@"\d+\b").Match(dbds.TableName).Success)
                {
                    string DocEntry = string.Empty;
                    string SerialNum = string.Empty;
                    IEnumerator fieldEnumerator = dbds.Fields.GetEnumerator();
                    while (fieldEnumerator.MoveNext())
                    {
                        SAPbouiCOM.Field field = fieldEnumerator.Current as SAPbouiCOM.Field;
                        if (field.Name == "DocEntry")
                        {
                            DocEntry = dbds.GetValue("DocEntry", dbds.Offset);
                        }
                        if (field.Name == "U_SerialNum")
                        {
                            SerialNum = dbds.GetValue("U_SerialNum", dbds.Offset);
                        }
                    }
                    string content = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "6").ToString().Trim();
                    Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                    rs.DoQuery(String.Format("select Name from OUDO where Code = '{0}'", ObjType));
                    if (rs.RecordCount > 0)
                    {
                        string objName = rs.Fields.Item("Name").Value;
                        //单据传送 海运-报价单 单据号 3 Q121100003 Eva Yang 2013-01-05
                        Utils.SendMessage(this.SBOCompany, "单据传送 " + objName + " 单据号:[" + DocEntry.ToString() + "] 流水号:[" + SerialNum.Trim() + "]", content, USER_CODE, DocEntry, SerialNum, objName);
                        SBOApp.StatusBar.SetText(String.Format("向“{0}”的消息发送成功！", userEngName), BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Success);
                    }
                    return true;
                }
            }
            return false;
        }
        private bool FeeSend(string UserCode)
        {
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(ParentFormUID);
            #region 加载需要的审核的数据
            string Table_BP = oForm.DataSources.UserDataSources.Item("BPTable").ValueEx;/*业务单操作 DBDS TableName*/
            SAPbouiCOM.DataTable Dt_Fee = ParentItemUID == "DSend" ? oForm.DataSources.DataTables.Item("DT_Rece") : oForm.DataSources.DataTables.Item("DT_Pay");
            int DocEntry_Order = 0;
            List<int> List_Order = new List<int>();
            for (int Row = 0; Row < Dt_Fee.Rows.Count; Row++)
            {
                if (Dt_Fee.GetValue("LineStatus", Row) == "O") /*费用行状态为"未清"*/
                {
                    DocEntry_Order = Dt_Fee.GetValue("DocEntry", Row);
                    if (!List_Order.Contains(DocEntry_Order))
                    {
                        List_Order.Add(DocEntry_Order);
                    }
                }
            }
            if (List_Order.Count == 0)
            {
                SBOApp.StatusBar.SetText("暂无需要审核的费用项...", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
                return false;
            }
            #endregion


            SAPbobsCOM.BoObjectTypes LinkObject = ParentItemUID == "DSend" ? BoObjectTypes.oOrders : BoObjectTypes.oPurchaseOrders;
            int errCode;
            string errMsg;
            SAPbobsCOM.Messages oMsgs;
            oMsgs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oMessages);

            string BoEntry = oForm.DataSources.UserDataSources.Item("BoEntry").ValueEx;
            string BoSerialNum = oForm.DataSources.UserDataSources.Item("BoSerial").ValueEx;
            #region 发送信息
            foreach (int OrderDocEntry in List_Order)
            {
                oMsgs.Subject = "费用单审核";
                oMsgs.MessageText = "请审核之后生成账单.\r\n" + SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "6").ToString().Trim();
                #region 收件人配置
                oMsgs.Recipients.Add();
                oMsgs.Recipients.UserCode = UserCode;
                oMsgs.Recipients.SendInternal = SAPbobsCOM.BoYesNoEnum.tYES;
                #endregion
                #region 信息内容
                oMsgs.AddDataColumn("业务单", string.Format("流水号:[{0}] - 业务单号:[{1}]", BoEntry, BoSerialNum), SAPbobsCOM.BoObjectTypes.oMessages, BoEntry);
                oMsgs.AddDataColumn("业务单客户", oForm.DataSources.UserDataSources.Item("CardName").ValueEx, BoObjectTypes.oBusinessPartners, oForm.DataSources.UserDataSources.Item("CardCode").ValueEx);
                oMsgs.AddDataColumn("费用单", OrderDocEntry.ToString(), LinkObject, OrderDocEntry.ToString());
                #endregion
                if (oMsgs.Add() != 0)
                {
                    SBOCompany.GetLastError(out errCode, out errMsg);
                    SBOApp.StatusBar.SetText("发送系统信息错误：" + errMsg);
                    return false;
                }
                oMsgs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oMessages);
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oMsgs);
            SBOApp.StatusBar.SetText("费用审核信息已发送至客服.", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
            #endregion
            return true;
        }
    }
}
